import extend from "extend";

export const getEvent = (event) => {
  event = event || window.event;
  if (!event) {
    return event;
  }
  if (!event.target) {
    event.target = event.srcElement;
  }
  if (!event.currentTarget) {
    event.currentTarget = event.srcElement;
  }
  return event;
};

export const getEventListenerMethod = () => {
  let addMethod = "addEventListener",
    removeMethod = "removeEventListener",
    prefix = "";
  if (!window.addEventListener) {
    addMethod = "attachEvent";
    removeMethod = "detachEvent";
    prefix = "on";
  }
  return {
    addMethod,
    removeMethod,
    prefix,
  };
};

export const getBoundingClientRect = (element) => {
  const rect = element.getBoundingClientRect();
  const width = rect.width || rect.right - rect.left;
  const heigth = rect.heigth || rect.bottom - rect.top;
  return extend({}, rect, {
    width,
    heigth,
  });
};

export const stringify = (obj) => {
  let params = [];
  for (let key in obj) {
    params.push(`${key}=${obj[key]}`);
  }
  return params.join("&");
};

export function getDomPath(element, useClass = false, trachingAttrName) {
  if (!(element instanceof HTMLElement)) {
    console.warn("input is not a HTML element!");
    return "";
  }
  let elem = element;
  return getDomDesc(elem, useClass, trachingAttrName);
}

export function getDomDesc(element, useClass = false, trachingAttrName) {
  if (!element || !element.tagName) {
    return "";
  }
  let isAttr = element.getAttribute(trachingAttrName);
  if (isAttr) {
    return isAttr;
  } else {
    let arrtName = getElementParents(element, trachingAttrName);
    return arrtName;
  }
}

function getElementParents(element, trachingAttrName) {
  if (!element || element.tagName === "BODY") return "";
  let parent = element.parentElement;
  let parentAttr = parent.getAttribute(trachingAttrName);
  if (parentAttr) {
    return parentAttr;
  } else {
    return getElementParents(parent, trachingAttrName);
  }
}

export function querySelector(queryString) {
  return (
    document.getElementById(queryString) ||
    document.getElementsByName(queryString)[0] ||
    document.querySelector(queryString)
  );
}
